//
//  NewsService.swift
//  SCA
//
//  Created by tjun on 2025/9/3.
//

import Foundation

enum NewsType: String {
    case news = "news"
    case guide = "guide"
}

struct NewsService {
    
    static func loadNewsData(limit: Int = 0, type: NewsType, success:(([NewsModel]) -> Void)? = nil,
                             failure:((_ error: Error) -> Void)? = nil) {
        
        var parameters: [String: Any] = [:]
        parameters["type"] = type.rawValue
        if limit > 0 {
            parameters["limit"] = limit
        }
        
        NetworkManager.shared.post(url: APIEndpoint.news, parameters: parameters, success: { data in
            guard let result = data as? [String: Any],
                  let content = result["content"] as? [String: Any] else {
                return
            }
            
            let datas = Array(content.values)
            
            let models: [NewsModel] = datas.compactMap { value in
                guard let dict = value as? [String: Any] else {
                    return nil
                }
                return NewsModel(
                    title: dict.stringValue("title"),
                    content: dict.stringValue("content")
                )
            }
            
            success?(models)
        }, failure: failure)
    }
    
    
    static func loadNewsListData(limit: Int = 0, type: NewsType, success:(([NewsListModel]) -> Void)? = nil,
                                 failure:((_ error: Error) -> Void)? = nil) {
        
        var parameters: [String: Any] = [:]
        parameters["type"] = type.rawValue
        if limit > 0 {
            parameters["limit"] = limit
        }
        
        NetworkManager.shared.post(url: APIEndpoint.news, parameters: parameters, success: { data in
            guard let result = data as? [String: Any],
                  let content = result["content"] as? [String: Any] else {
                return
            }
            
            let datas = Array(content.values)
            
            let models: [NewsListModel] = datas.compactMap { value in
                guard let dict = value as? [String: Any],
                      let displayType = dict["display_type"] as? String,
                      let Id = dict["id"] as? Int,
                      let title = dict["title"] as? String,

                      let content = dict["content"] as? String,
                      let cdate = dict["cdate"] as? String  else {
                    return nil
                }
                
                let url = dict["image"] as? String
                return NewsListModel(Id: Id, date: cdate, title: title, pageType: type, displayType: displayType, url: url, content: content)
            }
            
            let sortedModels = models.sorted { $0.Id > $1.Id }
            success?(sortedModels)
        }, failure: failure)
    }
    
}
